package com.controller;

import com.google.gson.Gson;
import com.pojo.Enterprise;
import com.pojo.SupplierBlackList;
import com.pojo.SupplierWhiteList;
import com.service.IEnterpriseService;
import com.service.ISupplierBlackListService;
import com.service.ISupplierWhiteListService;
import com.service.IUserService;
import com.service.impl.EnterpriseServiceImpl;
import com.service.impl.SupplierBlackListServciceImpl;
import com.service.impl.SupplierWhiteListServciceImpl;
import com.service.impl.UserServiceImpl;
import com.util.PageHelper;
import com.pojo.User;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.text.SimpleDateFormat;

@WebServlet("/blacklist/*")
public class SupplierBlackListController extends HttpServlet {
    private ISupplierBlackListService blackListService = new SupplierBlackListServciceImpl();
    private ISupplierWhiteListService whiteListService = new SupplierWhiteListServciceImpl();
    private IUserService userService = new UserServiceImpl();
    private IEnterpriseService enterpriseService = new EnterpriseServiceImpl();

    @Override
    /*重写 service 方法，实现请求的统一分发
根据请求 URI 的最后一段路径，反射调用对应的处理方法*/
    protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 获取请求的 URI，例如：/asd/blacklist/getBlackList
        String requestURI = request.getRequestURI();
        // 截取 URI 中最后一个 "/" 之后的部分作为方法名，例如：getBlackList
        int index = requestURI.lastIndexOf("/") + 1;
        String methodName = requestURI.substring(index);
        // 设置响应内容类型为 JSON，字符编码为 UTF-8，解决中文乱码问题
        response.setContentType("application/json;charset=UTF-8");
        response.setCharacterEncoding("UTF-8");

        try {
            // 通过反射获取当前类中与方法名匹配的方法，参数为 HttpServletRequest 和 HttpServletResponse
            Method method = this.getClass().getMethod(methodName, HttpServletRequest.class, HttpServletResponse.class);
            // 调用找到的方法，处理具体请求
            method.invoke(this, request, response);
        } catch (NoSuchMethodException | IllegalAccessException | InvocationTargetException e) {
            // 捕获反射相关异常，打印异常堆栈信息
            e.printStackTrace();
            // 向客户端返回 "方法未找到" 的 JSON 响应
            response.getWriter().println(new Gson().toJson("方法未找到"));
        }
    }

    /**
     * 获取黑名单数据 - 供前端页面调用
     * 前端调用路径: /asd/blacklist/getBlackList
     */
    public void getBlackList(HttpServletRequest request, HttpServletResponse response) throws IOException {
        try {
            // 从 Session 中获取当前登录用户的账号
            String account = (String) request.getSession().getAttribute("loginUser");
            // 如果用户未登录，返回 "用户未登录" 的响应
            if (account == null) {
                response.getWriter().println(new Gson().toJson("用户未登录"));
                return;
            }

            //  根据账号获取用户信息
            User user = userService.getUserByAccount(account);
            // 如果用户不存在或未关联企业，返回相应的错误信息
            if (user == null || user.getEnterpriseId() == null) {
                response.getWriter().println(new Gson().toJson("用户未关联企业"));
                return;
            }

            //  从请求参数中获取分页信息和搜索条件
            String pageStr = request.getParameter("page");
            String sizeStr = request.getParameter("size");
            String supplierName = request.getParameter("supplierName");
            String supplierLevel = request.getParameter("supplierLevel");
            // 处理分页参数，默认第一页，每页 5 条数据
            Integer page = (pageStr != null && !pageStr.isEmpty()) ? Integer.parseInt(pageStr) : 1;
            Integer size = (sizeStr != null && !sizeStr.isEmpty()) ? Integer.parseInt(sizeStr) : 5;

            PageHelper pageHelper;
            
            // 根据是否有搜索条件，选择不同的查询方法
            if ((supplierName != null && !supplierName.trim().isEmpty()) || 
                (supplierLevel != null && !supplierLevel.trim().isEmpty())) {
                // 有搜索条件，使用条件搜索
                pageHelper = blackListService.searchBlackListByCondition(
                    user.getEnterpriseId(), supplierName, supplierLevel, page);
            } else {
                // 无搜索条件，使用普通分页查询
                pageHelper = blackListService.getBlackListByPage(user.getEnterpriseId(), page);
            }
            
            // 获取详细的黑名单信息（包括企业信息）并构建包含详细信息的返回列表
            ArrayList<SupplierBlackList> blackList = (ArrayList<SupplierBlackList>) pageHelper.getListIndex();

            ArrayList<Map<String, Object>> detailedList = new ArrayList<>();
            // 用于格式化日期的工具类
            SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
            // 遍历黑名单列表，为每个条目补充详细信息
            for (SupplierBlackList item : blackList) {
                Map<String, Object> detailMap = new HashMap<>();
                detailMap.put("id", item.getId());
                detailMap.put("enterpriseId", item.getEnterpriseId());
                detailMap.put("supplierId", item.getSupplierId());
                detailMap.put("reason", item.getReason());
                detailMap.put("updateTime", item.getUpdateDate() != null ? dateFormat.format(item.getUpdateDate()) : "");
                
                // 获取供应商企业信息
                Enterprise supplier = enterpriseService.getEnterpriseById(item.getSupplierId());
                if (supplier != null) {
                    detailMap.put("supplierName", supplier.getName());
                    detailMap.put("contactPerson", supplier.getName()); // 使用企业名称作为联系人
                    detailMap.put("contactPhone", supplier.getPhone());
                    detailMap.put("contactEmail", supplier.getEmail());
                    detailMap.put("creditCode", supplier.getSocialUniformCode());
                } else {
                    detailMap.put("supplierName", "未知企业");
                    detailMap.put("contactPerson", "-");
                    detailMap.put("contactPhone", "-");
                    detailMap.put("contactEmail", "-");
                    detailMap.put("creditCode", "-");
                }
                
                detailedList.add(detailMap);
            }
            
            // 构建返回结果 - 按照前端期望格式
            Map<String, Object> result = new HashMap<>();
            result.put("content", detailedList);
            result.put("totalElements", pageHelper.getDataCount());
            result.put("totalPages", pageHelper.getPageCount());
            result.put("number", page - 1); // Spring Data JPA风格，页码从0开始
            result.put("size", size);
            result.put("numberOfElements", detailedList.size());
            result.put("first", page == 1);
            result.put("last", page >= pageHelper.getPageCount());
            
            response.getWriter().println(new Gson().toJson(result));
            
        } catch (Exception e) {
            e.printStackTrace();
            response.getWriter().println(new Gson().toJson("查询黑名单失败"));
        }
    }

    /**
     * 添加供应商到黑名单
     * 前端调用路径: /asd/blacklist/addToBlackList
     */
    public void addToBlackList(HttpServletRequest request, HttpServletResponse response) throws IOException {
        try {
            // 获取当前登录用户
            String account = (String) request.getSession().getAttribute("loginUser");
            if (account == null) {
                response.getWriter().println(new Gson().toJson("用户未登录"));
                return;
            }

            // 获取用户信息
            User user = userService.getUserByAccount(account);
            if (user == null || user.getEnterpriseId() == null) {
                response.getWriter().println(new Gson().toJson("用户未关联企业"));
                return;
            }

            // 获取参数
            String supplierIdStr = request.getParameter("supplierId");
            String reason = request.getParameter("reason");

            if (supplierIdStr == null || reason == null || reason.trim().isEmpty()) {
                response.getWriter().println(new Gson().toJson("参数不完整"));
                return;
            }

            Integer supplierId = Integer.parseInt(supplierIdStr);

            // 检查是否已在黑名单中
            if (blackListService.isInBlackList(user.getEnterpriseId(), supplierId)) {
                response.getWriter().println(new Gson().toJson("供应商已在黑名单中"));
                return;
            }

            // 从白名单中移除（如果存在）
            if (whiteListService.isInWhiteList(user.getEnterpriseId(), supplierId)) {
                whiteListService.delBlackList(user.getEnterpriseId(), supplierId);
            }

            // 创建黑名单记录
            SupplierBlackList blackList = new SupplierBlackList();
            blackList.setEnterpriseId(user.getEnterpriseId());
            blackList.setSupplierId(supplierId);
            blackList.setReason(reason.trim());
            blackList.setUpdateDate(new Date());

            // 添加到黑名单
            boolean success = blackListService.addBlackList(blackList);
            
            if (success) {
                response.getWriter().println(new Gson().toJson("添加成功"));
            } else {
                response.getWriter().println(new Gson().toJson("添加失败"));
            }

        } catch (Exception e) {
            e.printStackTrace();
            response.getWriter().println(new Gson().toJson("添加到黑名单失败"));
        }
    }

    /**
     * 从黑名单中移除供应商
     * 前端调用路径: /asd/blacklist/removeFromBlackList
     */
    public void removeFromBlackList(HttpServletRequest request, HttpServletResponse response) throws IOException {
        try {
            // 获取当前登录用户
            String account = (String) request.getSession().getAttribute("loginUser");
            if (account == null) {
                response.getWriter().println(new Gson().toJson("用户未登录"));
                return;
            }

            // 获取用户信息
            User user = userService.getUserByAccount(account);
            if (user == null || user.getEnterpriseId() == null) {
                response.getWriter().println(new Gson().toJson("用户未关联企业"));
                return;
            }

            // 获取参数
            String supplierIdStr = request.getParameter("supplierId");
            if (supplierIdStr == null) {
                response.getWriter().println(new Gson().toJson("参数不完整"));
                return;
            }

            Integer supplierId = Integer.parseInt(supplierIdStr);

            // 从黑名单中移除
            boolean success = blackListService.delBlackList(user.getEnterpriseId(), supplierId);
            
            if (success) {
                // 添加到白名单（可选，基于业务需求）
                if (!whiteListService.isInWhiteList(user.getEnterpriseId(), supplierId)) {
                    SupplierWhiteList whiteList = new SupplierWhiteList();
                    whiteList.setEnterpriseId(user.getEnterpriseId());
                    whiteList.setSupplierId(supplierId);
                    whiteList.setSupplierLevel("B"); // 默认评级
                    whiteList.setUpdateDate(new Date());
                    whiteListService.addWhiteList(whiteList);
                }
                
                response.getWriter().println(new Gson().toJson("移除成功"));
            } else {
                response.getWriter().println(new Gson().toJson("移除失败"));
            }

        } catch (Exception e) {
            e.printStackTrace();
            response.getWriter().println(new Gson().toJson("从黑名单中移除失败"));
        }
    }

    /**
     * 获取可添加到黑名单的企业列表（不在当前黑名单中的企业）
     */
    public void getAvailableEnterprises(HttpServletRequest request, HttpServletResponse response) throws IOException {
        try {
            // 获取当前登录用户
            String account = (String) request.getSession().getAttribute("loginUser");
            if (account == null) {
                response.getWriter().println(new Gson().toJson("用户未登录"));
                return;
            }

            // 获取用户信息
            User user = userService.getUserByAccount(account);
            if (user == null || user.getEnterpriseId() == null) {
                response.getWriter().println(new Gson().toJson("用户未关联企业"));
                return;
            }

            // 获取所有企业
            ArrayList<Enterprise> allEnterprises = enterpriseService.getAllEnterprises();
            ArrayList<Map<String, Object>> availableEnterprises = new ArrayList<>();
            
            for (Enterprise enterprise : allEnterprises) {
                // 排除自己的企业，并检查是否已在黑名单中
                if (!enterprise.getId().equals(user.getEnterpriseId()) && 
                    !blackListService.isInBlackList(user.getEnterpriseId(), enterprise.getId())) {
                    
                    Map<String, Object> enterpriseMap = new HashMap<>();
                    enterpriseMap.put("id", enterprise.getId());
                    enterpriseMap.put("name", enterprise.getName());
                    enterpriseMap.put("creditCode", enterprise.getSocialUniformCode());
                    enterpriseMap.put("contact", enterprise.getName()); // 使用企业名称作为联系人
                    enterpriseMap.put("phone", enterprise.getPhone());
                    enterpriseMap.put("email", enterprise.getEmail());
                    
                    availableEnterprises.add(enterpriseMap);
                }
            }
            
            response.getWriter().println(new Gson().toJson(availableEnterprises));
            
        } catch (Exception e) {
            e.printStackTrace();
            response.getWriter().println(new Gson().toJson("获取可用企业列表失败"));
        }
    }
}